﻿var filesHtml = {};
var url = new Url();
var $userId = url.GetQueryString("userId");
var $orderId = url.GetQueryString("orderId");
var serializer = new JSONSerializer();
var loanItems;
$(function () {//获取并绑定数据
    $("#verifyOpinion").attr("disabled", "disabled");
    $.getJSON("../Handler/LoanProductOrderHandler.ashx",
        { Type: 4, OrderId: $orderId, _: Math.random() },
        function (result) {
            if (result.Status) {
                updateProgress(result.Data);
                loanItems = result.Data.LoanItems;
                loadVerifyFiles(result.Data.Order.ProductTypeId);
                serializer.DeSerializeToSpan($(".orderInfo"), result.Data.Order);
                serializer.DeSerializeToSpan($(".userInfo"), result.Data.User);
                serializer.DeSerializeToSpan($(".workInfo"), result.Data.Work);
                serializer.DeSerializeToSpan($(".familyInfo"), result.Data.Family);
                serializer.DeSerializeToSpan($("#approvedInfo"), result.Data.Order);
                $("em[data-name='WorkEmail']").text(result.Data.Work.WorkEmail);
                $("em[data-name='IsHaveChildValue']").text(result.Data.Family.IsHaveChildValue);
                $("em[data-name='MaritalStatusValue']").text(result.Data.Family.MaritalStatusValue);
                $("em[data-name='HousePropertyValue']").text(result.Data.Family.HousePropertyValue);
                if (result.Data.ContractInfo) {
                    var contractInfo = result.Data.ContractInfo;
                    serializer.DeSerializeToSpan($("#contractArea"), result.Data.ContractInfo);
                    $("span[data-name='StartDate']").text(ChangeDateFormat(contractInfo.StartDate));
                    $("span[data-name='EndDate']").text(ChangeDateFormat(contractInfo.EndDate));
                    $("span[data-name='SignDate']").text(ChangeDateFormat(contractInfo.SignDate));
                }

                if (result.Data.Order.IsAgencyContract == 1) {
                    $("div.orgBankInfo").css("display", "block");
                    //查询机构信息
                    $("span[data-name='OrganizationName']").text(result.Data.Organization.Name);
                    $("span[data-name='OrgBankName']").text(result.Data.Organization.BankName);
                    $("span[data-name='OrgBankBranch']").text(result.Data.Organization.BankBranch);
                    $("span[data-name='OrgBankAccount']").text(result.Data.Organization.BankAccount);
                }

                //根据月还款额判断是否存在批核信息
                var repayPerMonth = $("span[data-name=RepayPerMonth]").text();
                if (repayPerMonth == "") {
                    $(".li3").css("display", "none");
                }
                else {
                    //单独绑定是否更换产品名称
                    $("div.isAccordanceProduct>span").text(result.Data.Order.IsAccordanceProduct ? "是" : "否");
                    if (result.Data.Order.IsAccordanceProduct) {
                        $("div.accordanceProduct").css("display", "block")
                            .children("span").text(result.Data.Order.ChangeProductName.split(',')[0]);
                    }

                    //单独绑定是否联名借款
                    $("div.isCoborrowLoan>span").text(result.Data.Order.IsAccordanceProduct ? "是" : "否");
                    if (result.Data.Order.IsAccordanceProduct) {
                        $("div.coborrowLoan").css("display", "block");
                        $("div.coborrowLoan>span").text(result.Data.Order.CoborrowName.split(',')[0]);
                    }
                }

                if (result.Data.Verify) {
                    $.each(result.Data.Verify, function (index, item) {
                        if (item.Index == 2) {
                            $("#verifyOpinion").val(item.AuditOpinion);
                        }
                    });
                }
                $.each(result.Data.LoanItems, function (index, item) {
                    if (!filesHtml["content" + item.AuthId]) {
                        filesHtml["content" + item.AuthId] = "";
                    }
                    $("#FileTemplate").tmpl(item.Files).appendTo($("#fileContent"));
                    filesHtml["content" + item.AuthId] += $("#fileContent").html();
                    $("#fileContent").empty();
                });
                                

                //借款订单是否更换产品
                if (result.Data.Order.ChangeProductName != "" && result.Data.Order.ChangeProductName != null) {

                    var str = result.Data.Order.ChangeProductName.split(',');
                    if (str.length == 2) {

                        //如果是分期贷
                        if (str[1] == 31021) {
                            $("#hidContractType").val(30);
                        }
                        else if (str[1] > 31021) {
                            $("#hidContractType").val(31);
                        } else {
                            $("#hidContractType").val(25);
                        }
                    }
                } else {
                    //是否机构签约
                    if (result.Data.Order.IsAgencyContract == 1) {
                        //如果是分期贷
                        if (result.Data.Order.ProductTypeId == 31021) {
                            $("#hidContractType").val(30);
                        }
                        else {
                            $("#hidContractType").val(31);
                        }
                    } else {
                        $("#hidContractType").val(25);
                    }
                }

                //显示合同Tab层
                $(".contract_generate").css("display", "block");
                loadContractInfo.GetDictionaryLoanTypeInfo();

            } else {
                alert(result.Message);
            }
        });

    $("#contractArea .text").change(function () {
        $(this).next("span").text("");
    });

    //提交合同
    $(".save_c1_wai .contractEffect,#contractRefuseInfo").click(function () {
        var obj = new Object();
        if ($(this).attr("data-state") == "false") {
            if ($("#txtreason").val().length == 0) {
                alert("合同退回意见不能为空！");
                return false;
            }
            obj.AuditOpinion = $("#txtreason").val();
        }
        obj.Passed = $(this).attr("data-state");
        obj.Type = 22,
        obj.OrderId = $orderId;
        $.ajax({
            type: "post",
            url: "../Handler/LoanProductOrderHandler.ashx",
            dataType: "json",
            async: true,
            data: obj,
            cache: false,
            complete: function () {
            },
            success: function (result) {
                if (result.Status) {
                    alert(result.Message);
                    location.href = "Handled.aspx?css=1031";
                }
                else {
                    alert("合同生效失败！");
                }

            }
        });
    });


    $(".fileList").click(function () {

        $.getJSON("../Handler/FileHandler.ashx", { OrderId: $orderId, type: 7, _: Math.random() }, function (result) {
            if (result == null) {
                $(".contract_list").text("暂无相关文件！");
            }
            else if (result.length > 0) {
                $("#contractlist").empty();
                $.each(result, function (index, item) {
                    $("#contractFileTemplate").tmpl(item).appendTo($("#contractlist"));
                });
                loadZoomScript();
            }
        });
    });

    //报表链接
    //$(".btnLoanAgreement").attr("href", "Rep_Loan_LoanAgreement.aspx?OrderId=" + $orderId);
    //$(".btnCreditAgreement").attr("href", "Rep_Loan_CreditAgreement.aspx?OrderId=" + $orderId);
    //$(".btnDebitAuth").attr("href", "Rep_Loan_DebitAuth.aspx?OrderId=" + $orderId);
    //$(".btnRepayReminder").attr("href", "Rep_Loan_RepayReminder.aspx?OrderId=" + $orderId);


    $(".queding_xia").hide();
    //退回
    $(".contractRefuse").click(function () {
        $(".caozuo").hide();
        $(".queding_xia").slideDown(500);
    });
    $(".return").click(function () {
        $(".reason").val("");
        $(".caozuo").show();
        $(".queding_xia").slideUp(500);
    });

});


//格式化日期
function ChangeDateFormat(cellval) {
    var date = new Date(parseInt(cellval.replace("/Date(", "").replace(")/", ""), 10));
    var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
    var currentDate = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
    return date.getFullYear() + "-" + month + "-" + currentDate;
}

//更新进度条
function updateProgress(data) {
    var total = 0, count = 5;
    if (data.Order) {
        total += 100 / count;
    }
    if (data.Family) {
        total += 100 / count;
    }
    if (data.User) {
        total += 100 / count;
    }
    if (data.Work) {
        total += 100 / count;
    }
    if (data.LoanItems && data.LoanItems.length > 0) {
        total += 100 / count;
    }
    total = parseInt(total);
    $(".progressBar").text(total + "%").css("width", total + "%");
}
//加载审核文件项目
function loadVerifyFiles(productId) {
    $.getJSON("../Handler/ProductHandler.ashx",
        { Id: productId, Type: 5, _: Math.random() },
        function (result) {
            if (result.Status) {
                $("#verifyList").empty();
                $.each(result.Data, function (index, item) {
                    $("#AuthentionTemplate").tmpl(item).appendTo("#verifyList").find(".openLayout").click(function () {
                        var authId = $(this).attr("data-authid");
                        $("#authId").val(authId);
                        $("#filelist").empty();
                        $("#filelist").html(filesHtml["content" + authId]);
                        loadZoomScript();
                    });
                });
                updateItemsStatus();
            } else {
                alert(result.Message);
            }
        });
}


//更新认证信息
function updateItemsStatus() {
    $.each(loanItems, function (index, item) {
        var dom = $("#verifyList div[data-authid='" + item.AuthId + "']");
        if (dom) {
            dom.attr("data-uploaded", true);
            if (item.Passed) {
                dom.find(".verifyStatus").text("已通过审核");
            }
            if (item.Files.length > 0) {
                dom.find(".uploadStatus").text("资料已上传");
                dom.find(".openLayout").show();
            }
        }
    });
    $("#verifyList").children("div:not('[data-uploaded]')").remove();
}
//添加预览脚本
function loadZoomScript() {
    $("#zoomScript").remove();
    $("#zoom").remove();
    var myScript = document.createElement("script");
    myScript.type = "text/javascript";
    myScript.id = "zoomScript";
    myScript.src = "../Plugins/gurdeZoom/js/zoom.min.js";
    document.body.appendChild(myScript);
}